package cn.itcast.controller;

import cn.itcast.common.Result;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(HttpSession session, HttpServletRequest request, String username, String password,Model m) {

        User user = userService.findByUsernameAndPassword(username, password);
        if (user == null) {
            return Result.createFail(1, "用户名或密码错误");
        }
        session.setAttribute("user", user);
        m.addAttribute("user", user);
        return Result.createSuccess();
    }

    @PostMapping("/addUser")
    @ResponseBody
    public Result addUser(HttpSession session,
                        HttpServletRequest request,
                          String user, String pwd) {
    	try {
    		userService.addUser(user, pwd);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.createFail();
		}
        return Result.createSuccess(0);
    }
    


}
